import { createRouter, createWebHistory } from 'vue-router'
import Login from '../views/login/index.vue'
import { useCounterStore } from '../stores/counter'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'login',
      component: Login,
    },
    {
      path: '/home',
      name: 'home',
      component: () => import('../views/home/index.vue'),
    },
  ],
})
// 路由守卫
router.beforeEach((to, from, next) => {
  const useStore = useCounterStore()
  if (to.name === 'login') {
    // 直接到login界面的
    next()
  } else {
    // 如果没登陆,不让跳转
    if (!useStore.token) {
      next({ name: 'login' })
    } else if (to.name !== from.name) {
      // 如果是同一个页面，不给跳转 --> 为了面包屑点击自己不跳转
      next()
    }
  }
})

export default router
